<?php

namespace office;

use PhpOffice\PhpSpreadsheet\{
	Spreadsheet,
	Writer\Xlsx,
	Cell\Cell,
};

class Excel
{
	/**
	 * 生成一个通用数据导出Excel文件
	 * @param array $columns 表格列，支持用.访问嵌套属性，支持回调，例如 ['name'=>'姓名', 'age'=>'性别', 'avatar.url'=>'头像', 'inviter'=>function($row, $cell, $rowIndex, $sheet){}]
	 * @param array $data 数据，例如 [['name'=>'张三', 'age'=>18], ['name'=>'李四', 'avatar'=>['url'=>'xxxx']]]
	 * @return string 文件的二进制内容，可使用 return download($data, 'file.xlsx', true); 下载到客户端
	 */
	public static function createExportTable($columns, $data)
	{
		// 创建一个新的Excel表格
		$spreadsheet = new Spreadsheet();
		$sheet = $spreadsheet->getActiveSheet();

		// 设置表头
		$colIndex = 1;
		foreach ($columns as $col) {
			$coordinate = [$colIndex, 1];
			$cell = $sheet->getCell($coordinate);
			if ($col instanceof \Closure) {
				$cell->setValue($col(null, $cell, 1, $sheet));
			} else {
				$cell->setValue($col);
			}
			$colIndex++;
		}

		$rowIndex = 2;
		foreach ($data as $item) {

			$colIndex = 1;

			foreach ($columns as $colKey => $col) {

				$coordinate = [$colIndex, $rowIndex];
				$cell = $sheet->getCell($coordinate);

				if ($col instanceof \Closure) {
					$nestedValue = $col($item, $cell, $rowIndex, $sheet);
				} else {
					// 处理嵌套字段
					$nestedKeys = explode('.', $colKey);
					$nestedValue = $item;
					foreach ($nestedKeys as $nestedKey) {
						$nestedValue = isset($nestedValue[$nestedKey]) ? $nestedValue[$nestedKey] : '';
					}
				}
				$sheet->setCellValue($coordinate, $nestedValue);
				$colIndex++;
			}
			$rowIndex++;
		}

		// 创建Excel文件
		$writer = new Xlsx($spreadsheet);

		ob_start();
		$writer->save('php://output');
		return ob_get_clean();
	}
}
